package xyz.apiote.stuff

import android.content.ContentValues
import android.content.Context
import android.content.ContextWrapper
import android.database.sqlite.SQLiteConstraintException
import android.database.sqlite.SQLiteDatabase

// todo consts

data class Stuff(val id: Long?, var name: String, var description: String, var container: Long)

class DB(context: ContextWrapper) {
	private var db: SQLiteDatabase = context.openOrCreateDatabase(
		"stuff",
		Context.MODE_PRIVATE, null
	)

	fun migrate() {
		db.execSQL("create table if not exists stuff(id integer primary key, name string, description string, container int, foreign key(container) references stuff(id));")
		try {
			db.execSQL(
				"insert into stuff values(?, ?, ?, ?)",
				arrayOf(0, "Stuff", "", -1)
			)
		} catch (e: SQLiteConstraintException) {
		}
	}

	fun saveStuff(stuff: Stuff): Array<Any> {
		db.rawQuery("select * from stuff where id = ?", arrayOf(stuff.id.toString())).use {
			return if (it.moveToNext()) {
				db.execSQL(
					"update stuff set name = ?, description = ?, container = ? where id = ?",
					arrayOf(stuff.name, stuff.description, stuff.container, stuff.id)
				)
				arrayOf(stuff.id!!, false)
			} else {
				val values = ContentValues()
				values.put("name", stuff.name)
				values.put("description", stuff.description)
				values.put("container", stuff.container)
				arrayOf(db.insert("stuff", null, values), true)
			}
		}
	}

	fun loadStuff(id: Long): Stuff {
		return db.rawQuery("select * from stuff where id = ?", arrayOf(id.toString())).use {
			val hasValue = it.moveToNext()
			assert(hasValue)
			val name = it.getString(1)
			val description = it.getString(2)
			val container = it.getLong(3)

			Stuff(id, name, description, container)
		}
	}

	fun loadContainer(containerID: Long): ArrayList<Stuff> {
		val stuff = ArrayList<Stuff>()
		db.rawQuery(
			"select * from stuff where container = ? order by name",
			arrayOf(containerID.toString())
		).use {
			while (it.moveToNext()) {
				val id = it.getLong(0)
				val name = it.getString(1)
				val description = it.getString(2)
				val container = it.getLong(3)
				stuff.add(Stuff(id, name, description, container))
			}
		}
		return stuff
	}

	fun deleteStuff(id: Long) {
		db.execSQL("delete from stuff where id = ?", arrayOf(id.toString()))
	}
}